<?php

/**
 * This file is part of the {@link http://ontowiki.net OntoWiki} project.
 *
 * @copyright Copyright (c) 2008, {@link http://aksw.org AKSW}
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
 */
 require_once("Importer.php");
/**
 * Component controller for the CSV Importer.
 *
 * @category OntoWiki
 * @package Extensions
 * @subpackage Csvimport
 * @copyright Copyright (c) 2010, {@link http://aksw.org AKSW}
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
 */
class DataCubeImporter extends Importer
{
    protected $measure;
    protected $dbhandle;
   
    public function parseFile() {
        $this->logEvent("Parsing file..");
        require_once 'CsvParser.php';
        $parser = new CsvParser($this->uploadedFile);
        $this->parsedFile = array_filter($parser->getParsedFile());
        $this->logEvent("File parsed!");
    }

    public function databaseConn($in_server, $in_user, $in_pwd, $in_db)
    {
        $this->dbhandle = mysql_connect($in_server, $in_user, $in_pwd);
        mysql_select_db($in_db);
    }

    public function importData() {
        $this->logEvent("Import started..");
        $this->db_createDimension();
        $this->db_createDataset();
        $this->db_saveData();
        $this->logEvent("Done saving data!");
    }

    public function createConfigurationView($urlBase) {
        $ontowiki = OntoWiki::getInstance();
        $model = $ontowiki->selectedModel;

        $this->view->scovo = true;

        $this->view->placeholder('main.window.title')->append('Import CSV Data');
        $this->view->actionUrl = $urlBase . 'csvimport/mapping';
        $this->view->salt = hash("md5", serialize($this->parsedFile));
        OntoWiki_Navigation::disableNavigation();

        if ($model->isEditable()) {

            $toolbar = $ontowiki->toolbar;
            $toolbar->appendButton(OntoWiki_Toolbar::ADD, array('name' => 'Add Dimension', 'id' => 'btn-add-dimension'))
                ->appendButton(OntoWiki_Toolbar::ADD, array('name' => 'Add Attribute', 'id' => 'btn-attribute', 'class'=>''))
                ->appendButton(OntoWiki_Toolbar::EDIT, array('name' => 'Select Data Range', 'id' => 'btn-datarange', 'class'=>''))
                ->appendButton(OntoWiki_Toolbar::SEPARATOR)
                ->appendButton(OntoWiki_Toolbar::SUBMIT, array('name' => 'Extract Triples', 'id' => 'extract'))
                ->appendButton(OntoWiki_Toolbar::RESET, array('name' => 'Cancel'));
            $this->view->placeholder('main.window.toolbar')->set($toolbar);


            $configurationMenu = OntoWiki_Menu_Registry::getInstance()->getMenu('Configurations');
            $i = 0;
            $pattern = '/\'/i';
            $replacement = "\\'";
            $this->view->configs = array();
            if(isset($this->storedConfigurations))
			{
                foreach ($this->storedConfigurations as $configNum => $config) {
                    $this->view->configs[$i] = preg_replace($pattern, $replacement, $config['config']);
                    $configurationMenu->prependEntry(
                            'Select ' . $config['label'],
                            'javascript:useCSVConfiguration(csvConfigs['.$i.'])'
                    );
                    $i++;
                }
            }

        $menu = new OntoWiki_Menu();
        $menu->setEntry('Configurations', $configurationMenu);

        $event = new Erfurt_Event('onCreateMenu');
        $event->menu = $configurationMenu;
        $this->view->placeholder('main.window.menu')->set($menu->toArray(false, true));



        } else {
            $ontowiki->appendMessage(
                #new OntoWiki_Message("No write permissions on model '{$this->view->modelTitle}'", OntoWiki_Message::WARNING)
            );
        }

        $this->view->table = $this->view->partial('partials/table.phtml', array(
                    'data' => $this->parsedFile,
                    'tableClass' => 'csvimport'
                ));
    }

    protected function _createDimensions() {
        $this->logEvent("Creating dimensions..");
        
        $ontowiki = OntoWiki::getInstance();
        
        if( !isset($this->configuration) ) die ("config not set!");

        $elements = array();

        // classes vars
        $type = $this->componentConfig->class->type;
        $label = $this->componentConfig->class->label;
        $value_predicate = $this->componentConfig->class->value;
        $subPropertyOf = $this->componentConfig->class->subPropertyOf;
        $comment = $this->componentConfig->class->comment;
        
        // qb vars
        $qbDimensionProperty = $this->componentConfig->qb->DimensionProperty;
        $qbconcept = $this->componentConfig->qb->concept;
        
        foreach ($this->configuration as $url => $dim) {

            echo "Key: $url; Value: $dim<br />\n";
            // filter blank stuff
            if(strlen($dim['label']) < 1) continue;
            
            // if it's attribute
            if($url == "uribase")
            {
                continue;
            }

            if( isset($dim['attribute']) && $dim['attribute'] == true){                
                // save measure
                $this->measures[] = array(
                    'url' => $url,
                    'uri' => $dim['uri'],
                    'label' => $dim['label'],
                    'value' => $dim['value']
                );
                
                // empty array
                $element = array();
                // class
                $element[$url] = array(
                    $type => array(
                        array(
                            'type' => 'uri',
                            'value' => $dim['uri']
                            )
                        ),
                    $label => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['label']
                            )
                        ),
                    $comment => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['value']
                        )
                    )
                );
                
                //$ontowiki->selectedModel->addMultipleStatements($element);
                $elements[] = $element;
                continue;
            }

            $element = array();

            // class
            $element[$url] = array(
                $type => array(
                    array(
                        'type' => 'uri',
                        'value' => $qbDimensionProperty
                        )
                    ),
                $label => array(
                    array(
                        'type' => 'literal',
                        'value' => $dim['label']
                        )
                    )
            );
            
            //cuando son todos numeros
            if( preg_match('/\D/', $dim['label']) <= 0  ){
                $element[$url] = array_merge($element[$url],
                    array(
                        $value_predicate => array(
                            array(
                                'type' => 'integer',
                                'value' => intval($dim['label'])
                            )
                        )
                    )
                );
            }
            
            // set subPropertyOf
            if( isset($dim['subproperty']) ){
                $element[$url] = array_merge($element[$url], 
                    array(
                        $subPropertyOf => array(
                            array(
                                'type' => 'uri',
                                'value' => $dim['subproperty']
                            )
                        )
                    )
                );
            }
            
            // set concept
            if( isset($dim['concept']) ){
                $element[$url] = array_merge($element[$url], 
                    array(
                        $qbconcept => array(
                            array(
                                'type' => 'uri',
                                'value' => $dim['concept']
                            )
                        )
                    )
                );
            }
            
            $elements[] = $element;

            // types
            // individuos de las nuevas dimensiones 

            foreach ($dim['elements'] as $eurl => $elem) {
                $element = array();

                // type of new dimension
                $element[$eurl] = array(
                    $type => array(
                        array(
                            'type' => 'uri',
                            'value' => $url
                            )
                        ),
                    $label => array(
                        array(
                            'type' => 'literal',
                            'value' => $elem['label']
                            )
                        )
                );
                $elements[] = $element;
            }

        }
        
        // create incidence
        $element = array();
        $element[$this->componentConfig->local->incidence->uri] = array(
            $type => array(
                array(
                    'type' => 'uri',
                    'value' => $this->componentConfig->local->incidence->type
                )
            ),
            $label => array(
                array(
                    'type' => 'literal',
                    'value' => $this->componentConfig->local->incidence->label
                )
            ),
            $subPropertyOf => array(
                array(
                    'type' => 'uri',
                    'value' => $this->componentConfig->local->incidence->subpropertyof
                )
            )
        );
        $elements[] = $element;
        
        $contents="";

        foreach ($elements as $elem) {
            //print_r($elem);
            $ontowiki->selectedModel->addMultipleStatements($elem);
            
            ob_start();
            print_r( $elem );
            $output = ob_get_clean();
            $contents = $contents.$output."\n";
        }

        $handle = fopen("/usr/share/ontowiki/extensions/olapimport/logs/dimensions.log", "w");
        fwrite($handle, $contents);
        fclose($handle);


        $this->logEvent("All dimensions created!");
    }
    
    protected function _createDataset(){
        $dimensions = $this->configuration;
        
        // objects
        $datastructDefinition = $this->componentConfig->qb->DataStructureDefinition;
        
        // predicates
        $type = $this->componentConfig->class->type;
        $component = $this->componentConfig->qb->component;
        
        // set url base
        $url_base = $this->componentConfig->local->setBase . "/".hash("md5", serialize($this->parsedFile))."/DataStructure";
        
        // create datastructure definition
        $element[$url_base] = array(
            $type => array(
                array(
                    'type' => 'uri',
                    'value' => $datastructDefinition
                )
            )
        );
        
        // append 
        $values = array();
        foreach($dimensions as $url => $dim){
            $values[] = array(
                'type' => 'uri',
                'value' => $url
            );
        }
        
        // merge values
        if( sizeof($values) > 0 ){
            $element[$url_base] = array_merge($element[$url_base],
                array(
                    $component => $values
                )
            );
        }
        
        // TODO: Add qb:attribute from sdmx-attribute: data set
        
        // save to store
        $ontowiki = OntoWiki::getInstance();
        $ontowiki->selectedModel->addMultipleStatements($element);

        $contents = "";

        ob_start();
        print_r( $element );
        $output = ob_get_clean();
        $contents = $contents.$output."\n";

        $handle = fopen("/Library/WebServer/Documents/Sites/OntoWiki/extensions/csvimport/logs/dataset.log", "w");
        fwrite($handle, $contents);
        fclose($handle);
    }


    protected function _saveData() {

        $contents = "";

        $this->logEvent("Saving data to knowledge base..");

        $ontowiki = OntoWiki::getInstance();
        $dimensions = $this->configuration;
        
        // dimensions array
        $dims = array();
        // predicates
        $type = $this->componentConfig->class->type;
        $dataset = $this->componentConfig->qb->dataset;
        $incidence = $this->componentConfig->local->incidence->uri;
        // objects
        $qbObservation = $this->componentConfig->qb->Observation;
        // item url base
        $url_base = $this->componentConfig->local->base . "/".hash("md5", serialize($this->parsedFile));
        // count
        $count = 0;

        foreach($dimensions as $url => $dim){
            if( isset($dim['elements']) ){
                foreach($dim['elements'] as $eurl => $elem){
                    $dims[] = array(
                        'uri' => $eurl,
                        'pred' => $url,
                        'row' => $elem['row'],
                        'col' => $elem['col'],
                        'items' => $elem['items']
                    );
                }
            }
        }
        
        foreach($this->parsedFile as $rowIndex => $row){
            // check for null data
            if(!isset($row) || $row == null) continue;

            // parse row
            foreach($row as $colIndex => $cell){
                // filter empty
                if(strlen($cell) > 0){
                    // fill item dimensions from all dims
                    $itemDims = array();
                    foreach($dims as $dim){
                        if(
                            $colIndex >= $dim['items']['start']['col'] && $colIndex <= $dim['items']['end']['col'] &&
                            $rowIndex >= $dim['items']['start']['row'] && $rowIndex <= $dim['items']['end']['row']
                        ){
                            if($dim['col'] == $colIndex || $dim['row'] == $rowIndex){
                                $itemDims[$dim['pred']][] = array(
                                            'type' => 'uri',
                                            'value' => $dim['uri']
                                            );
                            }
                        }
                    }

                    // if there is some dimensions
                    if(count($itemDims) > 0){
                        // empty elements
                        $element = array();
                        
                        // create item url
                        $eurl = $url_base."/c".$colIndex."-r".$rowIndex;
                        
                        // get attributes
                        $attributes = array();
                        foreach( $this->measures as $ind => $attr ){
                            $attributes[$attr['uri']] = array(
                                array(
                                    'type' => 'uri',
                                    'value' => $attr['url']
                                )
                            );
                        }
                        
                        // merge with dimensions
                        $element[$eurl] = array_merge(
                            $itemDims,
                            array(
                                $incidence => array(
                                    array(
                                        'type' => 'literal',
                                        'value' => floatval( $cell )
                                    )
                                ),
                                $type => array(
                                    array(
                                        'type' => 'uri',
                                        'value' => $qbObservation
                                    )
                                )
                            )
                        );
                        // merge with attributes
                        $element[$eurl] = array_merge($element[$eurl],$attributes);
                        
                        

                        //print_r($element);
                        //echo "---------------------------------------------------------------";
                        // write element
                        //var_dump($element);
                        //die;

                        $count++;
                        if($count%1000 == 0){
                            $this->logEvent("Total triples saved: ".$count.". Still working..");
                        }
                        $ontowiki->selectedModel->addMultipleStatements($element);

                        ob_start();
                        print_r( $element );
                        $output = ob_get_clean();
                        $contents = $contents.$output."\n";

                    }
                }
            }
        }

        $handle = fopen("/Library/WebServer/Documents/Sites/OntoWiki/extensions/csvimport/logs/data.log", "w");
        fwrite($handle, $contents);
        fclose($handle);


        $this->logEvent("Done!");
        //echo "<pre>";
        //print_r( $dims );
        //echo "</pre>";
    }

    protected function db_createDimension(){
        $server = "localhost";
        $user = "root";
        $pwd = "root";
        $db = "dadosgov";

        /****************************************************************/
        /*******************  Properties ********************************/
        /****************************************************************/

        $type = $this->componentConfig->class->type;
        //$type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        $label = $this->componentConfig->class->label;
        //$label = "http://www.w3.org/2000/01/rdf-schema#label";
        $property = $this->componentConfig->class->Property;
        //$property = "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property";
        $value_predicate = $this->componentConfig->class->value;
        //$value_predicate = "http://www.w3.org/1999/02/22-rdf-syntax-ns#value";
        $subPropertyOf = $this->componentConfig->class->subPropertyOf;
        //$subPropertyOf = "http://www.w3.org/2000/01/rdf-schema#subPropertyOf";
        $comment = $this->componentConfig->class->comment;
        //$comment = "http://purl.org/dc/elements/1.1/comment";
        $range = $this->componentConfig->class->range;
        //$range = "http://www.w3.org/2000/01/rdf-schema#range";

        /****************************************************************/
        /*******************  Classes DataCube **************************/
        /****************************************************************/
        
        $qbDatastructDefinition = $this->componentConfig->qb->DataStructureDefinition;
        //$qbDatastructDefinition = "http://purl.org/linked-data/cube#DataStructureDefinition";
        $qbDimensionProperty = $this->componentConfig->qb->DimensionProperty;
        //$qbDimensionProperty = "http://purl.org/linked-data/cube#DimensionProperty";
        $qbMeasureProperty = $this->componentConfig->qb->MeasureProperty;
        //$qbMeasureProperty = "http://purl.org/linked-data/cube#MeasureProperty";
        $qbObservation = $this->componentConfig->qb->Observation;
        //$qbObservation = "http://purl.org/linked-data/cube#Observation";
        $qbDataSet = $this->componentConfig->qb->DataSet;
        //$qbDataSet = "http://purl.org/linked-data/cube#DataSet";
        $obsValue = $this->componentConfig->local->incidence->subpropertyof;
        //$obsValue = "http://purl.org/linked-data/sdmx/2009/measure#ObsValue";

        /*$sdmxdimension =  "http://purl.org/linked-data/sdmx/2009/dimension#";
        $sdmxmeasure =  "http://purl.org/linked-data/sdmx/2009/measure#";
        $sdmxattribute = "http://purl.org/linked-data/sdmx/2009/attribute#";
        $sdmxconcept = "http://purl.org/linked-data/sdmx/2009/concept#";
        $sdmxcode = "http://purl.org/linked-data/sdmx/2009/code#";
        $sdmxmetadata =  "http://purl.org/linked-data/sdmx/2009/metadata#";
        $sdmxsubject =  "http://purl.org/linked-data/sdmx/2009/subject#";*/
        
        /****************************************************************/
        /*******************  properties DataCube ***********************/
        /****************************************************************/
         
        $qbattribute = $this->componentConfig->qb->attribute;
        //$qbattribute = "http://purl.org/linked-data/cube#attribute";
        $component = $this->componentConfig->qb->component;
        //$component = "http://purl.org/linked-data/cube#component";
        $qbconcept = $this->componentConfig->qb->concept;
        //$qbconcept = "http://purl.org/linked-data/cube#concept";


        /**********************************************************************************/
        /*******************  conexion con BD & set $this->dbhandle ***********************/
        /**********************************************************************************/

        $this->databaseConn($server, $user, $pwd, $db);

        $this->logEvent("Creating dimensions..");  
        $ontowiki = OntoWiki::getInstance();
        if( !isset($this->configuration) ) die ("config not set!");

        $filename = "/usr/share/ontowiki/extensions/olapimport/json/configOlapImport.json";
        $handle = fopen($filename, "r");
        $json = fread($handle, filesize($filename));
        fclose($handle);
        $configuration = json_decode($json, true);

        $elements = array();
        //foreach ($this->configuration as $url => $dim) 
        foreach ($configuration as $url => $dim) 
        {
            if($url == "uribase")
                continue;

            // if it's attribute
            if( isset($dim['attribute']) && $dim['attribute'] == true)
            {                
                // save measure
                $this->measures[] = array(
                    'url' => $url,
                    'uri' => $dim['uri'],
                    'label' => $dim['label']
                );
                
                // empty array
                $element = array();
                // class
                $element[$url] = array(
                    $type => array(
                        array(
                            'type' => 'uri',
                            'value' => $dim['uri']
                            )
                        ),
                    $label => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['label']
                            )
                        )
                );
                
                //$ontowiki->selectedModel->addMultipleStatements($element);
                $elements[] = $element;
                continue;
            }

            if(isset($dim['dimension']) && $dim['dimension'] == true)
            {
                $element = array();

                // class
                $element[$url] = array(
                    $type => array(
                        array(
                            'type' => 'uri',
                            'value' => $qbDimensionProperty
                            )
                        ),
                    $label => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['label_dimension']
                            )
                        )
                );
                
                //cuando son todos numeros
                if( preg_match('/\D/', $dim['label_dimension']) <= 0  ){
                    $element[$url] = array_merge($element[$url],
                        array(
                            $value_predicate => array(
                                array(
                                    'type' => 'integer',
                                    'value' => intval($dim['label_dimension'])
                                )
                            )
                        )
                    );
                }
                
                // set subPropertyOf
                if( isset($dim['subproperty']) ){
                    $element[$url] = array_merge($element[$url], 
                        array(
                            $subPropertyOf => array(
                                array(
                                    'type' => 'uri',
                                    'value' => $dim['subproperty']
                                )
                            )
                        )
                    );
                }
                
                // set concept
                if( isset($dim['concept']) ){
                    $element[$url] = array_merge($element[$url], 
                        array(
                            $qbconcept => array(
                                array(
                                    'type' => 'uri',
                                    'value' => $dim['concept']
                                )
                            )
                        )
                    );
                }
                
                $elements[] = $element;

                // individuos de las nuevas dimensiones
                
                $query  = "select ".$dim['column']." as label from ".$dim['table'];
                $res = mysql_query( $query, $this->dbhandle );
                while($row = mysql_fetch_array($res))
                {
                    $elabel = $row['label'];
                    $element = array();

                    $eurl = $url."/".urlencode($elabel);

                    $element[$eurl] = array(
                        $type => array(
                            array(
                                'type' => 'uri',
                                'value' => $url
                                )
                            ),
                        $label => array(
                            array(
                                'type' => 'literal',
                                'value' => $elabel
                                )
                            )
                    );
                    $elements[] = $element;                  
                }
            }
            if(isset($dim['measure']) && $dim['measure'] == true)
            {
                 // create incidence
                $element = array();
                $element[$url] = array(
                    $type => array(
                        array(
                            'type' => 'uri',
                            'value' => $property
                        ),
                        array(
                            'type' => 'uri',
                            'value' => $qbMeasureProperty
                        )
                    ),
                    $label => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['label']
                        )
                    ),
                    $subPropertyOf => array(
                        array(
                            'type' => 'uri',
                            'value' => $obsValue
                        )
                    ),
                    $range => array(
                        array(
                            'type' => 'uri',
                            'value' => $dim['range']
                        )
                    )
                );
                $elements[] = $element;
            }
        }

        $contents="";
        foreach ($elements as $elem) {
            $ontowiki->selectedModel->addMultipleStatements($elem);
            ob_start();
            print_r( $elem );
            $output = ob_get_clean();
            $contents = $contents.$output."\n";
        }
        $this->logEvent("All dimensions created!");
        $handle = fopen("/usr/share/ontowiki/extensions/olapimport/logs/dimension1.log", "w");
        fwrite($handle, $contents);
        fclose($handle);
    
    }

    protected function db_createDataset(){

        $server = "localhost";
        $user = "root";
        $pwd = "root";
        $db = "dadosgov";

        /**********************************************************************************/
        /*******************  conexion con BD & set $this->dbhandle ***********************/
        /**********************************************************************************/

        $this->databaseConn($server, $user, $pwd, $db);

        $datastructDefinition = $this->componentConfig->qb->DataStructureDefinition;
        //$datastructDefinition = "http://purl.org/linked-data/cube#DataStructureDefinition";
        $type = $this->componentConfig->class->type;
        //$type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        $label = $this->componentConfig->class->label;
        //$label = "http://www.w3.org/2000/01/rdf-schema#label";
        $component = $this->componentConfig->qb->component;
        //$component = "http://purl.org/linked-data/cube#component";
        $qbDataSet = $this->componentConfig->qb->DataSet;
        //$qbDataSet = "http://purl.org/linked-data/cube#DataSet";
        $comment = $this->componentConfig->class->comment;
        //$comment = "http://purl.org/dc/elements/1.1/comment";
        $qbstructure = $this->componentConfig->qb->structure;
        //$qbstructure = "http://purl.org/linked-data/cube#structure";

        $filename = "/usr/share/ontowiki/extensions/olapimport/json/configOlapImport.json";
        $handle = fopen($filename, "r");
        $json = fread($handle, filesize($filename));
        fclose($handle);
        $configuration = json_decode($json, true);

        //$dimensions = $this->configuration;
        $dimensions = $configuration;      

        $elements = array();
        $url_base = $dimensions["uribase"]."DataStructure";

        // create datastructure definition
        $element[$url_base] = array(
            $type => array(
                array(
                    'type' => 'uri',
                    'value' => $datastructDefinition
                )
            )
        );
        
        // append 
        $values = array();
        foreach($dimensions as $url => $dim)
        {
            if($url == "uribase")
                continue;
            if( (isset($dim['measure']) && $dim['measure'] == true) ||
                (isset($dim['attribute']) && $dim['attribute'] == true) ||
                (isset($dim['dimension']) && $dim['dimension'] == true))
            {
                $values[] = array(
                    'type' => 'uri',
                    'value' => $url
                ); 
            }
        }
        
        // merge values
        if( count($values) > 0 ){
            $element[$url_base] = array_merge($element[$url_base],
                array(
                    $component => $values
                )
            );
        }
        $elements[] = $element;
        
        $element = array();   
        $url_base_dataset = $dimensions["uribase"]."Dataset";     

        foreach($dimensions as $url => $dim)
        {
            if($url == "uribase")
                continue;
            if( (isset($dim['dataset']) && $dim['dataset'] == true))
            {
                $element[$url_base_dataset] = array(
                    $type => array(
                        array(
                            'type' => 'uri',
                            'value' => $qbDataSet
                        )
                    ),
                    $label => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['label']
                        )
                    ),
                    $comment => array(
                        array(
                            'type' => 'literal',
                            'value' => $dim['comment']
                        )
                    ),
                    $qbstructure => array(
                        array(
                            'type' => 'uri',
                            'value' => $url_base
                        )
                    )
                );
            }
        }

        $elements[] = $element;
        // save to store
        $ontowiki = OntoWiki::getInstance();
        foreach ($elements as $elem) {
            $ontowiki->selectedModel->addMultipleStatements($elem);
        }

        ob_start();
        print_r( $elements );
        $output = ob_get_clean();
        $handle = fopen("/usr/share/ontowiki/extensions/olapimport/logs/dataset1.log", "w");
        fwrite($handle, $output);
        fclose($handle);
    }

    protected function db_saveData() {

        $contents = "";

        $server = "localhost";
        $user = "root";
        $pwd = "root";
        $db = "dadosgov";

        /**********************************************************************************/
        /*******************  conexion con BD & set $this->dbhandle ***********************/
        /**********************************************************************************/

        $this->databaseConn($server, $user, $pwd, $db);

        $type = $this->componentConfig->class->type;
        //$type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        $label = $this->componentConfig->class->label;
        //$label = "http://www.w3.org/2000/01/rdf-schema#label";
        $comment = $this->componentConfig->class->comment;
        //$comment = "http://purl.org/dc/elements/1.1/comment";
        $dataset = $this->componentConfig->qb->dataset;
        //$dataset = "http://purl.org/linked-data/cube#dataset";
        $qbObservation = $this->componentConfig->qb->Observation;
        //$qbObservation = "http://purl.org/linked-data/cube#Observation";

        $filename = "/usr/share/ontowiki/extensions/olapimport/json/configOlapImport.json";
        $handle = fopen($filename, "r");
        $json = fread($handle, filesize($filename));
        fclose($handle);
        $configuration = json_decode($json, true);

        $this->logEvent("Saving data to knowledge base..");
        $ontowiki = OntoWiki::getInstance();
        //$dimensions = $this->configuration;
        $dimensions = $configuration; 
        
        // dimensions array
        $dims = array();

        // item url base
        //$url_base = $this->componentConfig->local->base . "/".hash("md5", serialize($this->parsedFile));
        $url_base = $dimensions["uribase"]."item/";
        // count
        $count = 0;
        $urls = array();
        $table_to = array();
        $column_to = array();
        $column_from = array();
        $column_value = array();

        foreach($dimensions as $url => $dim)
        {
            if($url == "uribase")
                continue;

            if( isset($dim['fact']) && $dim['fact'] == true)
            {
                if( isset($dim['dimensions']) )
                {
                    foreach($dim['dimensions'] as $eurl => $elem)
                    {
                        array_push($urls, $eurl);
                        array_push($table_to,$elem['to_table']);
                        array_push($column_to, $elem['to']);
                        array_push($column_from, $elem['from']);
                        array_push($column_value, $elem['column']);
                    }
                }
                $table_from = $dim['table'];
                $value =$dim['column'];
            }
            if(isset($dim['measure']) && $dim['measure'] == true)
            {
                $url_measure = $url;
            }
        }

        $tables = "";
        $columns = "";
        $where = "";

        for($cont=0; $cont<count($table_to); $cont++)
        {
            if($cont!=0)
                $where = $where." and ";
            $tables = $tables.$table_to[$cont]." as t".($cont+2).", ";
            $columns = $columns."t".($cont+2).".".$column_value[$cont]." as label".($cont+2).", ";
            $where = $where." t1.".$column_from[$cont]."= t".($cont+2).".".$column_to[$cont];

        }
        
        $query  = "select ".$columns." t1.".$value." as value from ".$tables.$table_from." as t1 where ".$where." limit 10 ";
        $res = mysql_query( $query, $this->dbhandle );

        while($row = mysql_fetch_array($res))
        {
            $itemDims = array();

            $cell = $row['value'];
            for($cont=0; $cont<count($table_to); $cont++)
            {
                $index = "label".($cont+2);
                $elabel = $row[$index];
                $eurl = $urls[$cont]."/".urlencode($elabel);

                $itemDims[$urls[$cont]][] = array(
                                            'type' => 'uri',
                                            'value' => $eurl
                                            );
            }
            
            $md5 = hash("md5", serialize($itemDims).$cell);
            $eurl = $url_base.$md5;
            if(count($itemDims) > 0)
            {
                $element = array();
                $element[$eurl] = array_merge(
                                $itemDims,
                                array(
                                    $url_measure => array(
                                        array(
                                            'type' => 'literal',
                                            'value' => floatval( $cell )
                                        )
                                    ),
                                    $type => array(
                                        array(
                                            'type' => 'uri',
                                            'value' => $qbObservation
                                        )
                                    )
                                )
                            );
            }

            // get attributes
            $attributes = array();
            foreach( $this->measures as $ind => $attr ){
                $attributes[$attr['uri']] = array(
                    array(
                        'type' => 'uri',
                        'value' => $attr['url']
                    )
                );
            }

            $element[$eurl] = array_merge($element[$eurl],$attributes); 
            $count++;
            if($count%1000 == 0){
                $this->logEvent("Total triples saved: ".$count.". Still working..");
            } 
            $ontowiki->selectedModel->addMultipleStatements($element);
            ob_start();
            print_r( $element );
            $output = ob_get_clean();
            $contents = $contents.$output."\n";
        }

        $handle = fopen("/usr/share/ontowiki/extensions/olapimport/logs/data1.log", "w");
        fwrite($handle, $contents);
        fclose($handle);

        $this->logEvent("Done!");
    }

}
